<template>
  <ProjectInfo
    :preview="true"
    :projectId="`${route.query.projectId}`"
    :reportType="'JJLBC'"
    :sign="true"
    :sync="true"
    :syncContent="'从方案同步信息'"
    @on-sync-header="onSyncHeader"
    @preview-file="previewFile"
    ref="projectInfoRef"
    :needSignatureCheck="true"
    @signature="handleSignature"
  />
  <ContentWrap class="chem-record-wrap">
    <div style="position: relative">
      <el-tabs v-model="activeTab" class="chem-tabs" tab-position="top" type="border-card">
        <el-tab-pane label="气象记录" name="weather">
          <WeatherCondition  ref="weatherRef" :weatherRecords="weather" @update-records="handleUpdateRecords" />
        </el-tab-pane>
        <el-tab-pane v-if="personalList.length>0" label="个体采样" name="personal">
          <div v-for="(item, idx) in personalList" :key="idx" class="record-item">
            <HarmfulFactorsRecord
              :labelName="`个体采样`"
              ref="harmfulFactorsRecordRef1"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'personal')"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="fixList.length>0" label="定点采样" name="fix">
          <div v-for="(item, idx) in fixList" :key="idx" class="record-item">
            <HarmfulFactorsRecord
              :labelName="`定点采样`"
              ref="harmfulFactorsRecordRef2"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'fix')"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="personalNoise.length>0" label="个体噪声" name="personalNoise">
          <div v-for="(item, idx) in personalNoise" :key="idx" class="record-item">
            <PersonalNoiseRecord
              :labelName="`个体噪声`"
              ref="personalNoiseRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'personalNoise')"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="fixNoise.length>0" label="定点噪声" name="fixNoise">
          <div v-for="(item, idx) in fixNoise" :key="idx" class="record-item">
            <FixNoiseRecord
              :labelName="`定点噪声`"
              ref="fixNoiseRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'fixNoise')"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="highTemperature.length>0" label="高温测量" name="highTemperature">
          <div v-for="(item, idx) in highTemperature" :key="idx" class="record-item">
            <HighTemperatureRecord
              :labelName="`高温测量`"
              ref="highTemperatureRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'highTemperature')"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane v-if="powerFrequency.length>0" label="工频电场" name="powerFrequency">
          <div v-for="(item, idx) in powerFrequency" :key="idx" class="record-item">
            <PowerFrequencyElectricFieldRecord
              :labelName="`工频电场`"
              ref="powerFrequencyElectricFieldRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'powerFrequency')"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane v-if="handTransmitted.length>0" label="手动振传" name="handTransmitted">
          <div v-for="(item, idx) in handTransmitted" :key="idx" class="record-item">
            <HandTransmittedVibrationRecord
              :labelName="`手动振传`"
              ref="handTransmittedVibrationRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'handTransmitted')"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="ultravioletRadiation.length>0" label="紫外辐射" name="ultravioletRadiation">
          <div v-for="(item, idx) in ultravioletRadiation" :key="idx" class="record-item">
            <UltravioletRadiationRecord
              :labelName="`紫外辐射`"
              ref="ultravioletRadiationRecordRef"
              :form-data="item"
              :type="activeTab"
              :weatherRecords="getSampleDate(item.samplingPeriod)"
              @change="onRecordChange(idx, $event, 'ultravioletRadiation')"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </ContentWrap>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted, provide } from 'vue'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import { useRoute, useRouter } from 'vue-router'
import { ProjectApi } from '@/api/dk/project'
import HarmfulFactorsRecord from './HarmfulFactorsRecord.vue'
import WeatherCondition from './WeatherCondition.vue'
import ProjectInfo from './ProjectInfo.vue'
import FixNoiseRecord from './FixNoiseRecord.vue'
import PersonalNoiseRecord from './PersonalNoiseRecord.vue'
import HighTemperatureRecord from './HighTemperatureRecord.vue'
import PowerFrequencyElectricFieldRecord from './PowerFrequencyElectricFieldRecord.vue'
import HandTransmittedVibrationRecord from './HandTransmittedVibrationRecord.vue'
import UltravioletRadiationRecord from './UltravioletRadiationRecord.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { FacilityLogApi } from '@/api/infra/facilitylog'

const activeTab = ref('')
const personalList = ref<any[]>([])
const fixList = ref<any[]>([])
const personalNoise = ref<any[]>([])
const fixNoise = ref<any[]>([])
const highTemperature = ref<any[]>([])
const powerFrequency = ref<any[]>([])
const handTransmitted = ref<any[]>([])
const ultravioletRadiation = ref<any[]>([])
const route = useRoute()
const router = useRouter()

defineOptions({ name: 'HarmfulFactorsIndex' })

interface WeatherRecord {
  id: string
  sampleDate: string
  temperature: string
  airPressure: string
  weather: string
  humidity: string
}

const weather = ref<WeatherRecord[]>([
  {
    id: '',
    sampleDate: '',
    temperature: '',
    airPressure: '',
    weather: '',
    humidity: ''
  }
])

const projectInfoRef = ref()
const weatherRef = ref()
const harmfulFactorsRecordRef1 = ref()
const harmfulFactorsRecordRef2 = ref()
const personalNoiseRecordRef = ref()
const fixNoiseRecordRef = ref()
const highTemperatureRecordRef = ref()
const powerFrequencyElectricFieldRecordRef = ref()
const handTransmittedVibrationRecordRef = ref()
const ultravioletRadiationRecordRef = ref()

// 处理签名事件
const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 签名前整体校验：所有 tab 组件下的表单与表格不能为空
const signatureCheck = (): boolean => {
  if (weatherRef.value) {
    var a = weatherRef.value.validateRequired()
    if (!a) {
      activeTab.value = 'weather'
      return false
    }
  }

  // 处理 v-for 生成的组件引用（为数组）
  const validateArrayRef = (arrRef: any, tabName: string): boolean => {
    const arr = arrRef?.value
    if (!arr) return true
    if (Array.isArray(arr)) {
      for (const comp of arr) {
        const ok = comp?.validateRequired ? comp.validateRequired() : true
        if (!ok) {
          activeTab.value = tabName
          return false
        }
      }
      return true
    }
    // 非数组时按单个组件处理
    const ok = arr?.validateRequired ? arr.validateRequired() : true
    if (!ok) {
      activeTab.value = tabName
      return false
    }
    return true
  }

  if (!validateArrayRef(harmfulFactorsRecordRef1, 'personal')) return false
  if (!validateArrayRef(harmfulFactorsRecordRef2, 'fix')) return false
  if (!validateArrayRef(personalNoiseRecordRef, 'personalNoise')) return false
  if (!validateArrayRef(fixNoiseRecordRef, 'fixNoise')) return false
  if (!validateArrayRef(highTemperatureRecordRef, 'highTemperature')) return false
  if (!validateArrayRef(powerFrequencyElectricFieldRecordRef, 'powerFrequency')) return false
  if (!validateArrayRef(handTransmittedVibrationRecordRef, 'handTransmitted')) return false
  if (!validateArrayRef(ultravioletRadiationRecordRef, 'ultravioletRadiation')) return false

  if (projectInfoRef.value) {
    projectInfoRef.value.showSignatureDialog()
  }
  // 字段中文名映射（未覆盖到的字段将回退为原 key 展示）
  return true
}

// 获取当前的气象情况 传递给组件
const getSampleDate = (samplingPeriod: number) => {
  var valueElement = weather.value[samplingPeriod - 1]
  console.log('父组件获取', JSON.stringify(valueElement))
  return valueElement
}

const handleUpdateRecords = (updatedRecords: WeatherRecord[]) => {
  weather.value = updatedRecords
  // 同步所有采样记录的 sampleDate
  const syncSampleDate = (list: any[]) => {
    list.forEach((item) => {
      const period = item.samplingPeriod || 1
      if (weather.value[period - 1]) {
        item.sampleDate = weather.value[period - 1].sampleDate
        item.airPressure = weather.value[period - 1].airPressure
        item.humidity = weather.value[period - 1].humidity
        item.weather = weather.value[period - 1].weather
      }
    })
  }
  syncSampleDate(personalList.value)
  syncSampleDate(fixList.value)
  syncSampleDate(personalNoise.value)
  syncSampleDate(fixNoise.value)
  syncSampleDate(powerFrequency.value)
  syncSampleDate(highTemperature.value)
  syncSampleDate(handTransmitted.value)
  syncSampleDate(ultravioletRadiation.value)
  ProjectApi.updateHarmfulFactorsRecord({
    projectId: route.query.projectId,
    personal: personalList.value,
    fix: fixList.value,
    personalNoise: personalNoise.value,
    fixNoise: fixNoise.value,
    highTemperature: highTemperature.value,
    powerFrequency: powerFrequency.value,
    handTransmitted: handTransmitted.value,
    ultravioletRadiation: ultravioletRadiation.value,
    weather: weather.value
  })
  ElMessage.success('修改成功')
}

/** 添加开始调查方法 */
const previewFile = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 8
    }
  })
}

const getHarmfulFactorsRecord = async () => {
  const projectId = route.query.projectId
  if (!projectId) return
  const response = await ProjectApi.getHarmfulFactorsRecord(Number(projectId))
  if (!response) return
  personalList.value = response.personal || []
  fixList.value = response.fix || []
  personalNoise.value = response.personalNoise || []
  fixNoise.value = response.fixNoise || []
  fixNoise.value = response.fixNoise || []
  highTemperature.value = response.highTemperature || []
  powerFrequency.value = response.powerFrequency || []
  handTransmitted.value = response.handTransmitted || []
  ultravioletRadiation.value = response.ultravioletRadiation || []
  weather.value = response.weather || []
  // 当天气返回为空的时候，不能赋值，如果赋值会覆盖默认值
  if (response.weather) {
    weather.value = response.weather
    console.log('天气数据', JSON.stringify(weather.value))
    weather.value.forEach((item) => {
      // 如果weather属性为空字符串或未定义，则设置为'晴天'
      if (!item.weather) {
        item.weather = '晴天'
      }
    })
  }
}

// 根据“工作场所+检测岗位”唯一原则，在同步时为每行分配默认的 sampleObjectLocation
const applyUniqueDefaultsForTables = (list: any[]) => {
  if (!Array.isArray(list)) return
  list.forEach((item) => {
    const table = item && Array.isArray(item.table) ? item.table : []
    // 分组：workplace + detectionPost
    const usedMap = new Map<string, Set<string>>()
    table.forEach((row: any) => {
      const wp = row?.workplace || ''
      const dp = row?.detectionPost || ''
      if (!wp || !dp) return
      const key = `${wp}||${dp}`
      if (!usedMap.has(key)) usedMap.set(key, new Set<string>())
    })

    table.forEach((row: any) => {
      const wp = row?.workplace || ''
      const dp = row?.detectionPost || ''
      if (!wp || !dp) {
        // 没有完整分组信息，不强制唯一，清空或保持为空
        const opts0: string[] = Array.isArray(row?.sampleObjectLocationed)
          ? row.sampleObjectLocationed
          : Array.isArray(row?.sampleObjectLocation)
            ? row.sampleObjectLocation
            : []
        // 同步时覆盖，若有可选项取第一项，否则置空
        row.sampleObjectLocation = opts0.length > 0 ? [opts0[0]] : []
        return
      }
      const key = `${wp}||${dp}`
      const used = usedMap.get(key) || new Set<string>()
      // 选项来源：优先 sampleObjectLocationed，其次 sampleObjectLocation（作为选项列表）
      let options: string[] = []
      if (Array.isArray(row?.sampleObjectLocationed) && row.sampleObjectLocationed.length > 0) {
        options = row.sampleObjectLocationed
      } else if (Array.isArray(row?.sampleObjectLocation) && row.sampleObjectLocation.length > 0) {
        options = row.sampleObjectLocation
        // 维护分离结构
        row.sampleObjectLocationed = [...options]
      } else {
        options = []
      }

      // 默认选择：取未被同组占用的第一项；若全部占用，置空
      const pick = options.find((o) => !used.has(o)) || ''
      row.sampleObjectLocation = pick ? [pick] : []
      if (pick) used.add(pick)
      usedMap.set(key, used)
    })
  })
}

const onSyncHeader = async () => {
  try {
    await ElMessageBox.confirm('已有数据将被覆盖，确认是否同步？', '确认同步', {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消'
    })
  } catch (_) {
    return
  }
  const projectId = route.query.projectId
  if (!projectId) return
  try {
    const results = await ProjectApi.getDefaultHarmfulFactorsRecord(Number(projectId))
    const { personalRes, fixRes, personalNoiseRes, fixNoiseRes, highTemperatureRes, weatherRes,powerFrequencyRes,handTransmittedRes,ultravioletRadiationRes } =
    results || {}
    // 合并数据，保留本地已填写内容
    // personalList.value = mergeList(fixList.value, personalRes || [])
    // fixList.value = mergeList(fixList.value, fixRes || [])
    // personalNoise.value = mergeList(personalNoise.value, personalNoiseRes || [])
    // fixNoise.value = mergeList(fixNoise.value, fixNoiseRes || [])

    personalList.value = personalRes || []
    fixList.value = fixRes || []
    personalNoise.value = personalNoiseRes || []
    fixNoise.value = fixNoiseRes || []
    highTemperature.value = highTemperatureRes || []
    powerFrequency.value = powerFrequencyRes || []
    ultravioletRadiation.value = ultravioletRadiationRes || []
    handTransmitted.value = handTransmittedRes || []
    weather.value = weatherRes || []
    console.log('天气数据', JSON.stringify(weather.value))

    // 同步时强制覆盖分配默认的 sampleObjectLocation（遵循唯一原则）
    applyUniqueDefaultsForTables(personalList.value)
    applyUniqueDefaultsForTables(fixList.value)
    applyUniqueDefaultsForTables(personalNoise.value)
    applyUniqueDefaultsForTables(fixNoise.value)
    applyUniqueDefaultsForTables(highTemperature.value)
    applyUniqueDefaultsForTables(powerFrequency.value)
    applyUniqueDefaultsForTables(handTransmitted.value)
    applyUniqueDefaultsForTables(ultravioletRadiation.value)

    await ProjectApi.updateHarmfulFactorsRecord({
      projectId: route.query.projectId,
      personal: personalList.value,
      fix: fixList.value,
      personalNoise: personalNoise.value,
      highTemperature: highTemperature.value,
      powerFrequency: powerFrequency.value,
      handTransmitted: handTransmitted.value,
      ultravioletRadiation: ultravioletRadiation.value,
      weather: weather.value,
      fixNoise: fixNoise.value
    })

    ElMessage.success('从方案同步成功')
  } catch (error) {
    console.error('fetchAllTabs获取数据失败:', error)
  }
}

// 设备可用性校验（提供给子组件）
type CheckEquipmentAvailabilityParams = {
  equipmentId: string
  startTime: string
  endTime: string
  sampleDate: string
  currentLogId?: number | null
  sampleNo?: string
}
const checkEquipmentAvailability = async (
  params: CheckEquipmentAvailabilityParams
): Promise<number | null> => {
  const { equipmentId, startTime, endTime, sampleDate, currentLogId, sampleNo } = params || ({} as any)
  if (!equipmentId || !startTime || !endTime || !sampleDate) {
    return null
  }
  const borrowStartTime = `${sampleDate} ${startTime}:00`
  const borrowEndTime = `${sampleDate} ${endTime}:00`

  const logId = await FacilityLogApi.createLog({
    projectId: route.query.projectId,
    equipmentId: equipmentId,
    borrowStartTime: borrowStartTime,
    borrowEndTime: borrowEndTime,
    logid: currentLogId ?? null,
    sampleNo: sampleNo ?? ''
  })
  return (typeof logId === 'number' ? logId : (logId?.data ?? logId)) ?? null
}

provide('checkEquipmentAvailability', checkEquipmentAvailability)

const onRecordChange = (idx: number, newData: any, tab: string) => {
  console.log(222222222222)
  console.log('onRecordChange', JSON.stringify(newData))
  if (tab === 'personal') {
    personalList.value.splice(idx, 1, { ...newData })
  } else if (tab === 'fix') {
    fixList.value.splice(idx, 1, { ...newData })
  } else if (tab === 'personalNoise') {
    personalNoise.value.splice(idx, 1, { ...newData })
  } else if (tab === 'fixNoise') {
    fixNoise.value.splice(idx, 1, { ...newData })
  } else if (tab === 'highTemperature') {
    highTemperature.value.splice(idx, 1, { ...newData })
  } else if (tab === 'powerFrequency') {
    powerFrequency.value.splice(idx, 1, { ...newData })
  } else if (tab === 'handTransmitted') {
    handTransmitted.value.splice(idx, 1, { ...newData })
  } else if (tab === 'ultravioletRadiation') {
    ultravioletRadiation.value.splice(idx, 1, { ...newData })
  }
  console.log('highTemperature触发:', JSON.stringify(highTemperature.value))
  // console.log('onRecordChange触发:', JSON.stringify({ idx, newData, tab }))
  // 直接在此处更新到服务器
  ProjectApi.updateHarmfulFactorsRecord({
    projectId: route.query.projectId,
    personal: personalList.value,
    fix: fixList.value,
    personalNoise: personalNoise.value,
    fixNoise: fixNoise.value,
    weather: weather.value,
    powerFrequency: powerFrequency.value,
    handTransmitted: handTransmitted.value,
    ultravioletRadiation: ultravioletRadiation.value,
    highTemperature: highTemperature.value
  })
}
// 初始化时获取数据

watch(activeTab, (val) => {
  localStorage.setItem('harmfulFactorsActiveTab', val)
})

onMounted(() => {
   activeTab.value =localStorage.getItem('harmfulFactorsActiveTab') || 'weather'
  getHarmfulFactorsRecord()
})
</script>

<style lang="scss" scoped>
.chem-tabs {
  // 保持极简无圆角无阴影
  :deep(.el-tabs__item) {
    font-size: 16px;
  }
}

.record-item {
  margin-bottom: 60px;
}
</style>
